package com.ruoyi.feike.instener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.activiti.domain.ActWorkflowFormData;
import com.ruoyi.activiti.mapper.ActWorkflowFormDataMapper;
import com.ruoyi.activiti.service.impl.ActTaskServiceImpl;
import com.ruoyi.activiti.service.impl.ActWorkflowFormDataServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.feike.controller.PdfController;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.feike.service.ICreditConditionService;
import com.ruoyi.feike.service.IDealerInformationService;
import com.ruoyi.feike.service.IProposalByCommericalAndMarketingService;
import com.ruoyi.feike.service.impl.AnnualReviewyServiceImpl;
import com.ruoyi.feike.service.impl.BasicInformationServiceImpl;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class RcEndStateListener implements ExecutionListener {

    private Expression state;


    @Override
    public void notify(DelegateExecution delegateExecution) {
        String instanceId = delegateExecution.getProcessInstanceBusinessKey();
        //判断下是不是走的第八个流程termination，是的话就只需要修改下flag表的数据
        AnnualReviewy annualReviewy1 = SpringUtils.getBean(AnnualReviewyMapper.class).selectAnnualReviewyByInstanceId(instanceId);
        if (annualReviewy1.getType().equals("termination")) {
            List<BasicInformation> basicInformations = SpringUtils.getBean(BasicInformationMapper.class).selectDealerGroupByByInstanceId(instanceId);
            for(BasicInformation pm : basicInformations){
                DealerSectorLimitflag dealerSectorLimitflag = new DealerSectorLimitflag();
                dealerSectorLimitflag.setDealername(pm.getDealerNameCN());
                List<DealerSectorLimitflag> dealerSectorLimitflags = SpringUtils.getBean(DealerSectorLimitflagMapper.class).selectDealerSectorLimitflagList(dealerSectorLimitflag);
                DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                    oldBean = dealerSectorLimitflags.get(0);
                }
                dealerSectorLimitflag.setNormalflag("true");
                dealerSectorLimitflag.setPartsFlag("true");
                dealerSectorLimitflag.setDemolflag("true");
                dealerSectorLimitflag.setTempflag("true");
                dealerSectorLimitflag.setMrgflag("true");
                dealerSectorLimitflag.setCbflag("true");
                dealerSectorLimitflag.setThreepartyflag("true");
                dealerSectorLimitflag.setIsTermination(1);

                SpringUtils.getBean(DealerSectorLimitflagMapper.class).updateDealerSectorLimitflagDealer(dealerSectorLimitflag);
                IAnnualReviewyService bean = SpringUtils.getBean(IAnnualReviewyService.class);
                bean.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,dealerSectorLimitflag,"CRO确认");
            }

        } else {

/*            ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = new ProposalByCommericalAndMarketing();
            proposalByCommericalAndMarketing.setInstanceId(instanceId);
            proposalByCommericalAndMarketing.setIsNew(1);
            List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketings = SpringUtils.getBean(IProposalByCommericalAndMarketingService.class).selectProposalByCommericalAndMarketingList(proposalByCommericalAndMarketing);
            if (null != proposalByCommericalAndMarketings && proposalByCommericalAndMarketings.size() > 0) {
                for (int i = 0; i < proposalByCommericalAndMarketings.size(); i++) {
                    ProposalByCommericalAndMarketing proposal = proposalByCommericalAndMarketings.get(i);
                    DealerInformation dealerInformation = new DealerInformation();
                    dealerInformation.setDealerName(proposal.getDealername());
                    dealerInformation.setMake(proposal.getSector());
                    dealerInformation.setDealerCode(proposal.getDealerCode());
                    SpringUtils.getBean(DealerInformationMapper.class).insertDealerInformation(dealerInformation);

                    //新增dealerinfomation表的同时，也要给flag表新增新经销商数据
                    if (StringUtils.isNotEmpty(proposal.getSector())) {
                        DealerSectorLimitflag dealerSectorLimitflag = new DealerSectorLimitflag();
                        dealerSectorLimitflag.setId(IdUtils.simpleUUID());
                        dealerSectorLimitflag.setDealername(proposal.getDealername());
                        dealerSectorLimitflag.setSector(proposal.getSector());
                        dealerSectorLimitflag.setNormalflag("true");
                        dealerSectorLimitflag.setPartsFlag("true");
                        dealerSectorLimitflag.setDemolflag("true");
                        dealerSectorLimitflag.setTempflag("true");
                        dealerSectorLimitflag.setMrgflag("true");
                        dealerSectorLimitflag.setCbflag("true");
                        dealerSectorLimitflag.setThreepartyflag("true");
                        SpringUtils.getBean(DealerSectorLimitflagMapper.class).insertDealerSectorLimitflag(dealerSectorLimitflag);
                    }
                }
            }*/
            //----------------------------------------------------------------------------------------
            //RC批复后把批复时间插进annual_reviewy表里
            AnnualReviewy annualReviewy = new AnnualReviewy();
            annualReviewy.setInstanceId(instanceId);
            annualReviewy.setUpdateTime(DateUtils.getNowDate());
            SpringUtils.getBean(AnnualReviewyMapper.class).updateAnnualReviewyByInstanceId(annualReviewy);
            //----------------------------------------------------------------------------------------
            //RC节点同意审批后调用该方法将生成的合同数据插入到新表里
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("instanceId", instanceId);
            SpringUtils.getBean(BasicInformationServiceImpl.class).contractnew(objectObjectHashMap);
            DealercodeContract dealercodeContract = new DealercodeContract();
            dealercodeContract.setInstanceId(instanceId);
            List<DealercodeContract> dealercodeContracts = SpringUtils.getBean(DealercodeContractMapper.class).selectDealercodeContractList(dealercodeContract);
            if (StringUtils.isNotEmpty(dealercodeContracts)) {
                //新表数据生成后通过分组合并不同的数据，再插入到归档表里、并且生成归档合同存放在文件夹里
                SpringUtils.getBean(PdfController.class).testpdf(objectObjectHashMap);
            }else {
                System.out.println(instanceId+"没有触发生成合同场景");
                AnnualReviewy annualReviewyTemp = new AnnualReviewy();
                annualReviewyTemp.setInstanceId(instanceId);
                annualReviewyTemp.setState("4");
                SpringUtils.getBean(AnnualReviewyMapper.class).updateAnnualReviewyByInstanceId(annualReviewyTemp);

                SecuritiesMapper securitiesMapper = SpringUtils.getBean(SecuritiesMapper.class);
                List<Securities> securities = securitiesMapper.selectSecuritiesByInstanceIdGroupName(instanceId);
                if(securities!=null && securities.size()>0){
                    for (Securities security : securities) {
                        List<Securities> securities1 = securitiesMapper.selectSecuritiesByInstanceIdAndName(instanceId, security.getDealername());
                        StringBuffer currentCN = new StringBuffer();
                        StringBuffer currentEN = new StringBuffer();
                        StringBuffer ProposalCN = new StringBuffer();
                        StringBuffer ProposalEN = new StringBuffer();
                        if(securities1!=null && securities1.size()>0){
                            for (Securities securities2 : securities1) {
                                if(securities2.getGuaranteeType()!=null){
                                    if(securities2.getGuaranteeType().equals("corporate")){
                                        if(!StringUtils.isEmpty(securities2.getProposalNameCN())){
                                            currentCN.append(securities2.getProposalNameCN()).append("#");
                                        }
                                        if(!StringUtils.isEmpty(securities2.getProposalNameEN())){
                                            currentEN.append(securities2.getProposalNameEN()).append("#");
                                        }
                                    }
                                    if(securities2.getGuaranteeType().equals("personal")){
                                        if(!StringUtils.isEmpty(securities2.getProposalNameCN())){
                                            ProposalCN.append(securities2.getProposalNameCN()).append("#");
                                        }
                                        if(!StringUtils.isEmpty(securities2.getProposalNameEN())){
                                            ProposalEN.append(securities2.getProposalNameEN()).append("#");
                                        }
                                    }
                                }
                            }
                        }
                        if (currentCN.length()>0) {
                            currentCN.deleteCharAt(currentCN.length() - 1);
                        }
                        if (currentEN.length()>0) {
                            currentEN.deleteCharAt(currentEN.length() - 1);
                        }
                        if (ProposalCN.length()>0) {
                            ProposalCN.deleteCharAt(ProposalCN.length() - 1);
                        }
                        if (ProposalEN.length()>0) {
                            ProposalEN.deleteCharAt(ProposalEN.length() - 1);
                        }
                        DealerInformationMapper dealerInformationMapper = SpringUtils.getBean(DealerInformationMapper.class);
                        List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByname(security.getDealername());
                        for (DealerInformation dealerInformation : dealerInformations) {
                            DealerInformation information = new DealerInformation();
                            BeanUtils.copyProperties(dealerInformation,information);
                            if(ProposalCN.length()>0){
                                dealerInformation.setIndividualGuarantorCn(ProposalCN.toString());
                            }else{
                                dealerInformation.setIndividualGuarantorCn(null);
                            }
                            if(ProposalCN.length()>0){
                                dealerInformation.setIndividualGuarantorEn(ProposalEN.toString());
                            }else{
                                dealerInformation.setIndividualGuarantorEn(null);

                            }
                            if(currentCN.length()>0){
                                dealerInformation.setCorporateGuarantorCn(currentCN.toString());
                            }else{
                                dealerInformation.setCorporateGuarantorCn(null);
                            }
                            if(currentEN.length()>0){
                                dealerInformation.setCorporateGuarantorEn(currentEN.toString());
                            }else{
                                dealerInformation.setCorporateGuarantorEn(null);
                            }
                            dealerInformationMapper.updateDealerInformationnew(dealerInformation);
                            IAnnualReviewyService bean = SpringUtils.getBean(IAnnualReviewyService.class);
                            bean.saveDbLog("3","修改经销商信息",null,instanceId,information,dealerInformation,"CRO确认");
                        }
                    }
                }

                HBasicCorporateGuaranteeMapper basicCorporateGuaranteeMapper = SpringUtils.getBean(HBasicCorporateGuaranteeMapper.class);
                HBasicCorporateGuarantee hBasicCorporateGuarantee = new HBasicCorporateGuarantee();
                hBasicCorporateGuarantee.setInstanceid(instanceId);
                List<HBasicCorporateGuarantee> hBasicCorporateGuarantees = basicCorporateGuaranteeMapper.selectHBasicCorporateGuaranteeListByName(hBasicCorporateGuarantee);
                if (hBasicCorporateGuarantees != null && hBasicCorporateGuarantees.size() > 0) {

                    for (HBasicCorporateGuarantee basicCorporateGuarantee : hBasicCorporateGuarantees) {
                        HBasicCorporateGuarantee hBasicCorporateGuarantee2 = new HBasicCorporateGuarantee();
                        hBasicCorporateGuarantee2.setInstanceid(instanceId);
                        hBasicCorporateGuarantee2.setDealername(basicCorporateGuarantee.getDealername());
                        List<HBasicCorporateGuarantee> hBasicCorporateGuarantees1 = basicCorporateGuaranteeMapper.selectHBasicCorporateGuaranteeList(hBasicCorporateGuarantee2);
                        if(hBasicCorporateGuarantees1!=null && hBasicCorporateGuarantees1.size()>0){
                            //开始组装
                            StringBuffer CorporateGuarantorJson = new StringBuffer();
                            for (HBasicCorporateGuarantee corporateGuarantee : hBasicCorporateGuarantees1) {
                                CorporateGuarantorJson.append(corporateGuarantee.getProposalNameCN()).append("#");
                                CorporateGuarantorJson.append(corporateGuarantee.getGuarantorindustry()).append("#");
                                CorporateGuarantorJson.append(corporateGuarantee.getGuarantorregioncode()).append("#");
                                CorporateGuarantorJson.append(corporateGuarantee.getGuarantorscale()).append(";");
                            }
                            if (StringUtils.isNotEmpty(CorporateGuarantorJson)){
                                CorporateGuarantorJson.deleteCharAt(CorporateGuarantorJson.length()-1);
                                DealerInformationMapper dealerInformationMapper = SpringUtils.getBean(DealerInformationMapper.class);
                                List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByname(basicCorporateGuarantee.getDealername());
                                for (DealerInformation dealerInformation : dealerInformations) {
                                    dealerInformation.setCorporateGuarantorJson(CorporateGuarantorJson.toString());
                                    System.out.println("更新担保信息");
                                    dealerInformationMapper.updateDealerInformationnew(dealerInformation);
                                }
                            }

                        }

                        HBasicCorporate hBasicCorporate2 = new HBasicCorporate();
                        hBasicCorporate2.setInstanceid(instanceId);
                        hBasicCorporate2.setDealername(basicCorporateGuarantee.getDealername());
                        HBasicCorporateMapper basicCorporateMapper = SpringUtils.getBean(HBasicCorporateMapper.class);
                        List<HBasicCorporate> hBasicCorporates1 = basicCorporateMapper.selectHBasicCorporateList(hBasicCorporate2);
                        if(hBasicCorporates1!=null && hBasicCorporates1.size()>0){
                            DealerInformationMapper dealerInformationMapper = SpringUtils.getBean(DealerInformationMapper.class);
                            List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByname(basicCorporateGuarantee.getDealername());
                            for (DealerInformation dealerInformation : dealerInformations) {
                                if(hBasicCorporates1!= null && hBasicCorporates1.size()>0){
                                    dealerInformation.setProvince(hBasicCorporates1.get(0).getProvince());
                                    dealerInformation.setCity(hBasicCorporates1.get(0).getCity());
                                    dealerInformation.setPeopleSum(hBasicCorporates1.get(0).getPeoplesum());
                                    dealerInformation.setEnterpriseType(hBasicCorporates1.get(0).getEnterprisetype());
                                    dealerInformation.setDownLoanAccount(hBasicCorporates1.get(0).getDownloanaccount());
                                    dealerInformationMapper.updateDealerInformationnew(dealerInformation);
                                }
                            }
                        }

                    }
                }
                BasicInformationMapper basicInformationMapper = SpringUtils.getBean(BasicInformationMapper.class);
                List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
                for (BasicInformation basicInformation : basicInformations) {
                    //更新最新的法人信息
                    DealerInformationMapper dealerInformationMapper = SpringUtils.getBean(DealerInformationMapper.class);
                    List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByname(basicInformation.getDealerNameCN());
                    if(dealerInformations !=null && dealerInformations.size()>0){
                        basicInformation.setNewLegalRepresentativeCN(dealerInformations.get(0).getLegalRepresentativeCN());
                        basicInformationMapper.updateBasicInformation(basicInformation);
                    }
                }

                return;
            }
            BasicInformationMapper basicInformationMapper = SpringUtils.getBean(BasicInformationMapper.class);
            List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
            for (BasicInformation basicInformation : basicInformations) {
                //更新最新的法人信息
                DealerInformationMapper dealerInformationMapper = SpringUtils.getBean(DealerInformationMapper.class);
                List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByname(basicInformation.getDealerNameCN());
                if(dealerInformations !=null && dealerInformations.size()>0){
                    basicInformation.setNewLegalRepresentativeCN(dealerInformations.get(0).getLegalRepresentativeCN());
                    basicInformationMapper.updateBasicInformation(basicInformation);
                }
            }
            //往归档表里插RC批复信息
            DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
            dealercodeContractFiling.setInstanceId(instanceId);
            dealercodeContractFiling.setRcIssueDate(DateUtils.getNowDate());
            SpringUtils.getBean(DealercodeContractFilingMapper.class).updateDealercodeContractFilingInstanceId(dealercodeContractFiling);
        }

        SecuritiesMapper securitiesMapper = SpringUtils.getBean(SecuritiesMapper.class);
        List<Securities> securities = securitiesMapper.selectSecuritiesByInstanceIdGroupName(instanceId);
        if(securities!=null && securities.size()>0){
            for (Securities security : securities) {
                List<Securities> securities1 = securitiesMapper.selectSecuritiesByInstanceIdAndName(instanceId, security.getDealername());
                StringBuffer currentCN = new StringBuffer();
                StringBuffer currentEN = new StringBuffer();
                StringBuffer ProposalCN = new StringBuffer();
                StringBuffer ProposalEN = new StringBuffer();
                if(securities1!=null && securities1.size()>0){
                    for (Securities securities2 : securities1) {
                        if(securities2.getGuaranteeType()!=null){
                            if(securities2.getGuaranteeType().equals("corporate")){
                                if(!StringUtils.isEmpty(securities2.getProposalNameCN())){
                                    currentCN.append(securities2.getProposalNameCN()).append("#");
                                }
                                if(!StringUtils.isEmpty(securities2.getProposalNameEN())){
                                    currentEN.append(securities2.getProposalNameEN()).append("#");
                                }
                            }
                            if(securities2.getGuaranteeType().equals("personal")){
                                if(!StringUtils.isEmpty(securities2.getProposalNameCN())){
                                    ProposalCN.append(securities2.getProposalNameCN()).append("#");
                                }
                                if(!StringUtils.isEmpty(securities2.getProposalNameEN())){
                                    ProposalEN.append(securities2.getProposalNameEN()).append("#");
                                }
                            }
                        }
                    }
                }
                if (currentCN.length()>0) {
                    currentCN.deleteCharAt(currentCN.length() - 1);
                }
                if (currentEN.length()>0) {
                    currentEN.deleteCharAt(currentEN.length() - 1);
                }
                if (ProposalCN.length()>0) {
                    ProposalCN.deleteCharAt(ProposalCN.length() - 1);
                }
                if (ProposalEN.length()>0) {
                    ProposalEN.deleteCharAt(ProposalEN.length() - 1);
                }
                DealerInformationMapper dealerInformationMapper = SpringUtils.getBean(DealerInformationMapper.class);
                List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByname(security.getDealername());
                for (DealerInformation dealerInformation : dealerInformations) {
                    DealerInformation information = new DealerInformation();
                    BeanUtils.copyProperties(dealerInformation,information);
                    if(ProposalCN.length()>0){
                        dealerInformation.setIndividualGuarantorCn(ProposalCN.toString());
                    }else{
                        dealerInformation.setIndividualGuarantorCn(null);
                    }
                    if(ProposalCN.length()>0){
                        dealerInformation.setIndividualGuarantorEn(ProposalEN.toString());
                    }else{
                        dealerInformation.setIndividualGuarantorEn(null);

                    }
                    if(currentCN.length()>0){
                        dealerInformation.setCorporateGuarantorCn(currentCN.toString());
                    }else{
                        dealerInformation.setCorporateGuarantorCn(null);
                    }
                    if(currentEN.length()>0){
                        dealerInformation.setCorporateGuarantorEn(currentEN.toString());
                    }else{
                        dealerInformation.setCorporateGuarantorEn(null);
                    }
                    dealerInformationMapper.updateDealerInformationnew(dealerInformation);
                    IAnnualReviewyService bean = SpringUtils.getBean(IAnnualReviewyService.class);
                    bean.saveDbLog("3","修改经销商信息",null,instanceId,information,dealerInformation,"CRO确认");
                }
            }
        }

        HBasicCorporateGuaranteeMapper basicCorporateGuaranteeMapper = SpringUtils.getBean(HBasicCorporateGuaranteeMapper.class);
        HBasicCorporateGuarantee hBasicCorporateGuarantee = new HBasicCorporateGuarantee();
        hBasicCorporateGuarantee.setInstanceid(instanceId);
        List<HBasicCorporateGuarantee> hBasicCorporateGuarantees = basicCorporateGuaranteeMapper.selectHBasicCorporateGuaranteeListByName(hBasicCorporateGuarantee);
        if (hBasicCorporateGuarantees != null && hBasicCorporateGuarantees.size() > 0) {

            for (HBasicCorporateGuarantee basicCorporateGuarantee : hBasicCorporateGuarantees) {
                HBasicCorporateGuarantee hBasicCorporateGuarantee2 = new HBasicCorporateGuarantee();
                hBasicCorporateGuarantee2.setInstanceid(instanceId);
                hBasicCorporateGuarantee2.setDealername(basicCorporateGuarantee.getDealername());
                List<HBasicCorporateGuarantee> hBasicCorporateGuarantees1 = basicCorporateGuaranteeMapper.selectHBasicCorporateGuaranteeList(hBasicCorporateGuarantee2);
                if(hBasicCorporateGuarantees1!=null && hBasicCorporateGuarantees1.size()>0){
                    //开始组装
                    StringBuffer CorporateGuarantorJson = new StringBuffer();
                    for (HBasicCorporateGuarantee corporateGuarantee : hBasicCorporateGuarantees1) {
                        CorporateGuarantorJson.append(corporateGuarantee.getProposalNameCN()).append("#");
                        CorporateGuarantorJson.append(corporateGuarantee.getGuarantorindustry()).append("#");
                        CorporateGuarantorJson.append(corporateGuarantee.getGuarantorregioncode()).append("#");
                        CorporateGuarantorJson.append(corporateGuarantee.getGuarantorscale()).append(";");
                    }
                    if (StringUtils.isNotEmpty(CorporateGuarantorJson)){
                        CorporateGuarantorJson.deleteCharAt(CorporateGuarantorJson.length()-1);
                        DealerInformationMapper dealerInformationMapper = SpringUtils.getBean(DealerInformationMapper.class);
                        List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByname(basicCorporateGuarantee.getDealername());
                        for (DealerInformation dealerInformation : dealerInformations) {
                            dealerInformation.setCorporateGuarantorJson(CorporateGuarantorJson.toString());
                            System.out.println("更新担保信息");
                            dealerInformationMapper.updateDealerInformationnew(dealerInformation);
                        }
                    }

                }

                HBasicCorporate hBasicCorporate2 = new HBasicCorporate();
                hBasicCorporate2.setInstanceid(instanceId);
                hBasicCorporate2.setDealername(basicCorporateGuarantee.getDealername());
                HBasicCorporateMapper basicCorporateMapper = SpringUtils.getBean(HBasicCorporateMapper.class);
                List<HBasicCorporate> hBasicCorporates1 = basicCorporateMapper.selectHBasicCorporateList(hBasicCorporate2);
                if(hBasicCorporates1!=null && hBasicCorporates1.size()>0){
                    DealerInformationMapper dealerInformationMapper = SpringUtils.getBean(DealerInformationMapper.class);
                    List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByname(basicCorporateGuarantee.getDealername());
                    for (DealerInformation dealerInformation : dealerInformations) {
                        if(hBasicCorporates1!= null && hBasicCorporates1.size()>0){
                            dealerInformation.setProvince(hBasicCorporates1.get(0).getProvince());
                            dealerInformation.setCity(hBasicCorporates1.get(0).getCity());
                            dealerInformation.setPeopleSum(hBasicCorporates1.get(0).getPeoplesum());
                            dealerInformation.setEnterpriseType(hBasicCorporates1.get(0).getEnterprisetype());
                            dealerInformation.setDownLoanAccount(hBasicCorporates1.get(0).getDownloanaccount());
                            dealerInformationMapper.updateDealerInformationnew(dealerInformation);
                        }
                    }
                }

            }
        }



        //注入实例对象
        RuntimeService runtimeService = SpringUtils.getBean(RuntimeService.class);
        ProcessRuntime processRuntime = SpringUtils.getBean(ProcessRuntime.class);
        DealercodeContractFilingMapper dealercodeContractFilingMapper = SpringUtils.getBean(DealercodeContractFilingMapper.class);
        HDealerDmMapper dmMapper = SpringUtils.getBean(HDealerDmMapper.class);
        SysUserMapper userMapper = SpringUtils.getBean(SysUserMapper.class);
        AnnualReviewyMapper bean = SpringUtils.getBean(AnnualReviewyMapper.class);
        DealerInformationMapper informationMapper = SpringUtils.getBean(DealerInformationMapper.class);
        BasicInformationMapper basicInformationMapper = SpringUtils.getBean(BasicInformationMapper.class);
        ActWorkflowFormDataMapper formDataMapper = SpringUtils.getBean(ActWorkflowFormDataMapper.class);
        ActTaskServiceImpl actTaskService = SpringUtils.getBean(ActTaskServiceImpl.class);
        SysPostMapper postMapper = SpringUtils.getBean(SysPostMapper.class);

        TaskService taskService = SpringUtils.getBean(TaskService.class);
        //绑定自合同子流程id
        DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
        dealercodeContractFiling.setInstanceId(instanceId);
        List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(dealercodeContractFiling);
        if(CollectionUtil.isNotEmpty(dealercodeContractFilings)){
            for (DealercodeContractFiling contractFiling : dealercodeContractFilings) {
                contractFiling.setSort(typeSort(contractFiling.getLimitType()));
            }
            dealercodeContractFilings.sort(Comparator.comparingInt(DealercodeContractFiling::getSort));

            Collections.sort(dealercodeContractFilings, new Comparator<DealercodeContractFiling>() {
                @Override
                public int compare(DealercodeContractFiling o1, DealercodeContractFiling o2) {
                    return o1.getDealerNameCN().compareTo(o2.getDealerNameCN());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });

            for (DealercodeContractFiling contractFiling : dealercodeContractFilings) {
                System.out.println("排序为："+contractFiling.getLimitType());
            }
            //遍历合同数，生成子流程
            for (DealercodeContractFiling contractFiling : dealercodeContractFilings) {
                org.activiti.engine.runtime.ProcessInstance parentInstance = runtimeService.createProcessInstanceQuery()
                        .processInstanceBusinessKey(instanceId)
                        .singleResult();

                //获取日期毫秒最后两位
                String s = Convert.toStr(System.currentTimeMillis());
                Integer integer = Integer.valueOf(s.substring(s.length() - 2));
                //加上随机数
                Random random = new Random();
                Integer num = random.nextInt(9)+1;
                //相加
                String id =  instanceId+"-"+DateUtils.addDate(new Date(), Calendar.SECOND, integer);
                id = id + num;
                //获取经销商对应的dm用户昵称
//                HDealerDm hDealerDm = dmMapper.selectHDealerDmByDealerName(contractFiling.getDealerNameCN());

                AnnualReviewy masterAnnualReviewy = bean.selectAnnualReviewyByInstanceId(instanceId);

//                SysUser sysUser1 = userMapper.selectUserByUserName(masterAnnualReviewy.getCreateBy());

//                ActWorkflowFormData actWorkflowFormDataByBusinessKey = formDataMapper.getActWorkflowFormDataByBusinessKey(instanceId);


                SysUser sysUser = userMapper.selectUserByUserName(masterAnnualReviewy.getCreateBy());
                Long userId = sysUser.getUserId();
                String nickName = sysUser.getNickName();
                String userName = sysUser.getUserName();

                //判断经销商是否存在
//                if(ObjectUtil.isNotNull(hDealerDm)){
//                    SysUser sysUser2 = userMapper.selectUserByNickName(hDealerDm.getDmName());
//                    if(ObjectUtil.isNotEmpty(sysUser2)){
//                        userId = sysUser2.getUserId();
//                        nickName = sysUser2.getNickName();
//                        userName = sysUser2.getUserName();
//                    }
//                }


                //设置发起人
                    Authentication.setAuthenticatedUserId(userId.toString());


                    ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                            .start()
                            .withProcessDefinitionKey("startContract")
                            .withName("startContract")
                            .withBusinessKey(id)
                            .withVariable("parentId", instanceId)
                            .build());


                Task task = taskService.createTaskQuery()
                        .processInstanceId(processInstance.getId())
                        .singleResult();

                    contractFiling.setSubProcessId(id);
                    dealercodeContractFilingMapper.updateDealercodeContractFiling(contractFiling);
                    AnnualReviewy annualReviewy = new AnnualReviewy();
                    annualReviewy.setId(IdUtils.simpleUUID());
                    annualReviewy.setInstanceId(id);
                    annualReviewy.setTitle("startContract");
                    annualReviewy.setType("startContract");  // TODO 待确认，先不填
                    annualReviewy.setCreateTime(DateUtils.getNowDate());
                    annualReviewy.setState("0");
                    annualReviewy.setSector(contractFiling.getSector());
                    annualReviewy.setCreateName(nickName);
                    annualReviewy.setCreateBy(userName);
                    annualReviewy.setCreateTime(DateUtils.getNowDate());
                    annualReviewy.setDealerName(contractFiling.getDealerNameCN());
                    annualReviewy.setSector(contractFiling.getSector());
                    annualReviewy.setStartNode("合同生成");
                    annualReviewy.setLimitType(contractFiling.getLimitType());
                    bean.insertAnnualReviewy(annualReviewy);



                    //获取经销商信息
                    List<DealerInformation> dealerInformations = informationMapper.selectDealerInformationByname(contractFiling.getDealerNameCN());
                    if(CollectionUtil.isNotEmpty(dealerInformations)){
                        BasicInformation basicInformation = new BasicInformation();
                        basicInformation.setId(IdUtils.simpleUUID());
                        basicInformation.setDealerNameCN(dealerInformations.get(0).getDealerName());
                        basicInformation.setDealerNameEN(dealerInformations.get(0).getEnName());
                        basicInformation.setGroupNameEN(dealerInformations.get(0).getGroupName());
                        basicInformation.setSector(contractFiling.getSector());
                        basicInformation.setInstanceId(id);
                        basicInformationMapper.insertBasicInformation(basicInformation);
                    }
            }

            List<SysUser> op = postMapper.selectUserListByPostCode("op");

            for (SysUser sysUser : op) {
                //发送待办邮件
                try {
                    actTaskService.sendMailByEmailInfo(sysUser,instanceId,false,null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }



        }
    }

    public  Integer typeSort(String type){
        String substring = type.substring(0, 1);
        if(substring.equalsIgnoreCase("N")){
            return 6;
        }
        if(substring.equalsIgnoreCase("D")){
            return 5;
        }
        if(substring.equalsIgnoreCase("T")){
            return 4;
        }
        if(substring.equalsIgnoreCase("C")){
            return 3;
        }
        if(substring.equalsIgnoreCase("M")){
            return 2;
        }
        return 1;
    }
}
